import 'package:easydubbing/utils/FutureDioToken.dart';
import 'package:easydubbing/utils/SpUtil.dart';
import 'package:easydubbing/utils/api.dart';
import 'package:easydubbing/utils/style.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'homePage.dart';


class LoginWidget extends StatefulWidget{
  _LoginWidgetState createState() => _LoginWidgetState();
}
class _LoginWidgetState extends State<LoginWidget>{

  TextEditingController accountEditingController;
  TextEditingController passwordEditingController;
  TextEditingController confirmPasswordEditingController;
  bool isShowPwd;
  bool isShowClear;
  bool isRegister;

  @override
  void initState() {
    isShowPwd = false;
    isShowClear = false;
    isRegister = false;
//    if(SpUtil.sharedPreferences.getBool('isLogin')!=null && !SpUtil.sharedPreferences.getBool('isLogin')){
//      setState(() {
//        isRegister = true;
//      });
//    }
    accountEditingController = new TextEditingController();
    accountEditingController.addListener(() {
      if(accountEditingController.text!=''){
        setState(() {
          isShowClear = true;
        });
      }else{
        setState(() {
          isShowClear = false;
        });
      }
    });
    passwordEditingController = new TextEditingController();
    confirmPasswordEditingController = new TextEditingController();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(!isRegister?'登录':'注册'),
        elevation: 0.5,
        brightness: Brightness.light,
        backgroundColor: ProjectColor.mainColor,
      ),
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: (){
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Container(
          child: Column(
            children: <Widget>[
              Container(
                width: 100,
                margin: EdgeInsets.only(top: 30,bottom: 20),
                child: Image.asset('assets/icons/logo.png'),
              ),
              Container(
                child: Container(
                  height: 50,
                  width: 300,
                  decoration: BoxDecoration(
                      color: Color(0xFFF2F3F5),
                      borderRadius: BorderRadius.all(Radius.circular(30))
                  ),
                  child: Row(
                    children: <Widget>[
                      Container(
                        margin:EdgeInsets.only(top: 5,left: 5,bottom: 5),
                        child: ClipOval(
                          child: AnimatedCrossFade(
                              sizeCurve: ElasticOutCurve(),
                              firstCurve: Curves.ease,
                              secondCurve: Curves.ease,
                              duration: Duration(milliseconds: 300),
                              firstChild: Image.asset('assets/icons/logo.png'),
                              secondChild: SizedBox(width: 40,height: 40,),
                              crossFadeState: accountEditingController.value.text=='admin'?
                              CrossFadeState.showFirst:CrossFadeState.showSecond
                          ),
                        ),
                      ),
                      Container(
                        width: 200,
                        margin: EdgeInsets.only(bottom: 5,left: 5,),
                        child: TextField(
                          cursorColor: Color(0xFFBBBBBB),
                          cursorWidth: 1,
                          controller: accountEditingController,
                          maxLines: 1,
                          inputFormatters: [
                            LengthLimitingTextInputFormatter(11),
                            FilteringTextInputFormatter.digitsOnly
                          ],
                          keyboardType:TextInputType.number,
                          decoration: InputDecoration(
                            hintText: '请输入电话',
                            hintStyle: TextStyle(color: Color(0xFFbbbbbb)),
                            border: InputBorder.none,
                          ),
                        ),
                      ),
                      Spacer(),
                      InkWell(
                        onTap: (){
                          accountEditingController.clear();
                        },
                        child:isShowClear?Icon(Icons.clear,size: 15,color: Color(0xFFcccccc),):SizedBox(),
                      ),
                      Spacer(),
                    ],
                  ),
                ),
              ),
              Container(
                child: Container(
                  height: 50,
                  width: 300,
                  margin: EdgeInsets.only(top: 20),
                  decoration: BoxDecoration(
                      color: Color(0xFFF2F3F5),
                      borderRadius: BorderRadius.all(Radius.circular(30))
                  ),
                  child: Row(
                    children: <Widget>[
                      Container(
                        width: 200,
                        margin: EdgeInsets.only(bottom: 5,left: 50),
                        child: TextField(
                          cursorColor: Color(0xFFBBBBBB),
                          cursorWidth: 1,
                          controller: passwordEditingController,
                          maxLines: 1,
                          decoration: InputDecoration(
                            hintText: '请输入密码',
                            hintStyle: TextStyle(color: Color(0xFFbbbbbb)),
                            border: InputBorder.none,
                          ),
                          obscureText: !isShowPwd,
                        ),
                      ),
                      Spacer(),
                      InkWell(
                        onTap: (){
                          setState(() {
                            isShowPwd = !isShowPwd;
                          });
                        },
                        child:isShowPwd?Icon(Icons.visibility,size: 15,color: Color(0xFFcccccc),):Icon(Icons.visibility_off,size: 15,color: Color(0xFFcccccc),),
                      ),
                      Spacer(),
                    ],
                  ),
                ),
              ),
              !isRegister?SizedBox():Container(
                child: Container(
                  height: 50,
                  width: 300,
                  margin: EdgeInsets.only(top: 20),
                  decoration: BoxDecoration(
                      color: Color(0xFFF2F3F5),
                      borderRadius: BorderRadius.all(Radius.circular(30))
                  ),
                  child: Row(
                    children: <Widget>[
                      Container(
                        width: 200,
                        margin: EdgeInsets.only(bottom: 5,left: 50),
                        child: TextField(
                          cursorColor: Color(0xFFBBBBBB),
                          cursorWidth: 1,
                          controller: confirmPasswordEditingController,
                          maxLines: 1,
                          decoration: InputDecoration(
                            hintText: '请输入确认密码',
                            hintStyle: TextStyle(color: Color(0xFFbbbbbb)),
                            border: InputBorder.none,
                          ),
                          obscureText: !isShowPwd,
                        ),
                      ),
                      Spacer(),
                      InkWell(
                        onTap: (){
                          setState(() {
                            isShowPwd = !isShowPwd;
                          });
                        },
                        child:isShowPwd?Icon(Icons.visibility,size: 15,color: Color(0xFFcccccc),):Icon(Icons.visibility_off,size: 15,color: Color(0xFFcccccc),),
                      ),
                      Spacer(),
                    ],
                  ),
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: 20),
                alignment: Alignment.center,
                child: InkWell(
                  highlightColor: Colors.transparent,
                  hoverColor: Colors.transparent,
                  splashColor: Colors.transparent,
                  onTap: (){
                    print(isRegister);
                    if(accountEditingController.value.text==''||accountEditingController.value.text.length!=11){
                      showDialog(
                          context: context,
                          builder: (context){
                            return AlertDialog(
                              shape:RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                              title: Text('提示'),
                              content: SingleChildScrollView(
                                child: ListBody(
                                  children: <Widget>[
                                    Text('电话格式不正确'),
                                  ],
                                ),
                              ),
                              actions: <Widget>[
                                TextButton(
                                  child: Text('确定',style: TextStyle(color: Color(0xFFF16050)),),
                                  onPressed: () {
                                    Navigator.pop(context);
                                  },
                                ),
                              ],
                            );
                          }
                      );
                    }
                    else if(passwordEditingController.value.text==''){
                      showDialog(
                          context: context,
                          builder: (context){
                            return AlertDialog(
                              shape:RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                              title: Text('提示'),
                              content: SingleChildScrollView(
                                child: ListBody(
                                  children: <Widget>[
                                    Text('请输入密码'),
                                  ],
                                ),
                              ),
                              actions: <Widget>[
                                TextButton(
                                  child: Text('确定',style: TextStyle(color: Color(0xFFF16050)),),
                                  onPressed: () {
                                    Navigator.pop(context);
                                  },
                                ),
                              ],
                            );
                          }
                      );
                    }
                    else if(isRegister&&passwordEditingController.value.text!=confirmPasswordEditingController.value.text){
                      showDialog(
                          context: context,
                          builder: (context){
                            return AlertDialog(
                              shape:RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                              title: Text('提示'),
                              content: SingleChildScrollView(
                                child: ListBody(
                                  children: <Widget>[
                                    Text('两次密码不一致!'),
                                  ],
                                ),
                              ),
                              actions: <Widget>[
                                TextButton(
                                  child: Text('确定',style: TextStyle(color: Color(0xFFF16050)),),
                                  onPressed: () {
                                    Navigator.pop(context);
                                  },
                                ),
                              ],
                            );
                          }
                      );
                    }
                    else{
                      FutureDio('post', isRegister?Api.register:Api.login, {
                        "phone":accountEditingController.value.text,
                        "password":passwordEditingController.value.text
                      }).then((value) {
                        if(value.data["msg"]!=null && value.data["msg"]!='ok'){
                          showDialog(
                              context: context,
                              builder: (context){
                                return AlertDialog(
                                  shape:RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                                  title: Text('提示'),
                                  content: SingleChildScrollView(
                                    child: ListBody(
                                      children: <Widget>[
                                        Text(isRegister?'注册失败':'用户或密码不正确'),
                                      ],
                                    ),
                                  ),
                                  actions: <Widget>[
                                    TextButton(
                                      child: Text('确定',style: TextStyle(color: Color(0xFFF16050)),),
                                      onPressed: () {
                                        Navigator.pop(context);
                                      },
                                    ),
                                  ],
                                );
                              }
                          );
                        }else {
                          if (value.data["msg"] == 'ok') {
                            setState(() {
                              isRegister = false;
                            });
                            Fluttertoast.showToast(
                                msg: '注册成功',
                                toastLength: Toast.LENGTH_SHORT,
                                gravity: ToastGravity.BOTTOM,
                                backgroundColor: Colors.black38,
                                textColor: Colors.white,
                                fontSize: 16.0
                            );
                          } else {
                            SpUtil.sharedPreferences.setBool('isLogin', true);
                            SpUtil.sharedPreferences.setInt(
                                'uid', value.data['data']['uid']);
                            SpUtil.sharedPreferences.setString(
                                'alias', value.data['data']['alias']??"");
                            SpUtil.sharedPreferences.setString(
                                'avatar', value.data['data']['avatar']??"");
                            SpUtil.sharedPreferences.setString(
                                'desc', value.data['data']['desc']??'');
                            SpUtil.sharedPreferences.setInt(
                                'isPro', value.data['data']['isPro']);
                            SpUtil.sharedPreferences.setInt(
                                'isVip', value.data['data']['isVip']);
                            Navigator.pushAndRemoveUntil(context,
                                new MaterialPageRoute(
                                    builder: (context) => new HomePage()),
                                    (route) => false);
                          }
                        }
                      });
                    }
                  },
                  child: ClipOval(
                    child: Container(
                      height: 50,
                      width: 50,
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                          colors: [
                            ProjectColor.deepColor,
                            ProjectColor.mainColor,

                          ],
                        ),
                      ),
                      child: Icon(Icons.arrow_forward,color: Colors.white),
                    ),
                  ),
                ),
              ),
              Spacer(),
              Container(
                margin: EdgeInsets.only(bottom: 20),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    InkWell(
                      onTap:(){
                        setState(() {
                          isRegister = !isRegister;
                        });
                      },
                      child: Text(isRegister?'登录  ':'注册账号 ',style: TextStyle(color: ProjectColor.deepColor),),
                    ),
                    Text('|',style: TextStyle(color: ProjectColor.secColor),),
                    Text(' 忘记密码',style: TextStyle(color: ProjectColor.deepColor),)
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

}